import axios from "axios";
import { CODE, RequireURL } from "./const";
// @ts-ignore
import { ElMessage } from "element-plus";

const request = axios.create({
    baseURL: RequireURL
});

request.interceptors.request.use((config) => {
    
    return config;
}, err => {
    console.log(err);
});

request.interceptors.response.use(
    async (res) => {
        if (res.headers["content-type"] === "application/json; charset=utf-8" && res.data instanceof Blob) {
            // 下载文件传递的是json数据的时候需要解析，报错
            const content = res.data;
            const blob = new Blob([content], { type: "application/json; charset=utf-8" });
            let text = await blob.text()
            res.data = JSON.parse(text);
            return Promise.reject(res.data.meg)
        } else if (res.status === 200 && res.data instanceof Blob) {
            // 表示下载文件成功
            return res;
        }
        return res;
    },
    async (err) => {
        // console.log(err);
        if( axios.isCancel(err) ){
            return Promise.reject(err)
        }
        let blob = new Blob([err.response.data], { type: "application/json; charset=utf-8" })
        let text = await blob.text()
        if(JSON.parse(text).code === CODE.needLogin ){
            localStorage.clear()
            location.reload();
        }
        if( err.response.status == 404 ){
            err.message = "资源获取失败，请检查路径是否正确"
        }
        ElMessage.error(err.message)
    }
);

export default request;
